#!/usr/bin/env python

import os
import subprocess
import socket
import sys
import time
from struct import *

import paho.mqtt.client as mqtt

first_connection = 1

def on_connect(mqttc, obj, flags, rc):
    global first_connection
    if rc != 0:
        exit(rc)
    else:
        if first_connection == 1:
            mqttc.publish("pub/qos2/test", "message", 2)
            first_connection = 0

def on_disconnect(mqttc, obj, rc):
    if rc == 1:
        mqttc.reconnect()
    else:
        run = 0

def on_publish(mqttc, obj, mid):
    mqttc.disconnect()

mqttc = mqtt.Client("publish-qos2-test", clean_session=False)
mqttc.message_retry_set(3)
mqttc.on_connect = on_connect
mqttc.on_disconnect = on_disconnect
mqttc.on_publish = on_publish

mqttc.connect("localhost", 1888)
rc = 0
while True:
    rc = mqttc.loop()
